<template>
	<view class="avatar-upload-container">
		<!-- 头像展示区域 -->
		<view class="avatar-container" :style="{
        width: size + 'px',
        height: size + 'px',
        borderColor: borderColor,
        borderWidth: borderWidth + 'px',
        borderRadius: shape === 'circle' ? '50%' : '8px',
      }" @click="handleActionSheet">
			<!-- 头像图片 -->
			<image v-if="avatarUrl || userStore.getUserInfo()" :src="avatarUrl || userStore.getUserInfo().avatar"
				class="avatar-image" :style="{ borderRadius: shape === 'circle' ? '50%' : '8px' }" mode="aspectFill">
			</image>

			<!-- 默认头像 -->
			<view v-else class="default-avatar" :style="{ borderRadius: shape === 'circle' ? '50%' : '8px' }">
				<up-avatar :src="avatarUrl" :size="size + 'px'" mode="aspectFill"></up-avatar>
			</view>

			<!-- 上传提示 -->
			<!-- <view class="upload-overlay">
        <view class="upload-icon">
          <uni-icons type="camera" size="24" color="#fff"></uni-icons>
        </view>
      </view> -->
		</view>

		<!-- 操作菜单 -->
		<view class="action-btns">
			<uni-action-sheet v-if="showActionSheetVisible" :list="actionSheetItems" @click="handleActionSheet"
				@close="showActionSheetVisible = false"></uni-action-sheet>
		</view>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		watch,
		defineProps,
		defineEmits,
		defineExpose,
		onMounted,
		onUnmounted
	} from "vue";
	import {
		useUserStore
	} from "@/store/user";
	import {
		onLoad,
		onShow
	} from "@dcloudio/uni-app";
	// 获取store实例
	const userStore = useUserStore();

	// 定义组件参数
	const props = defineProps({
		value: {
			type: String,
			default: "",
		},
		size: {
			type: Number,
			default: 150,
		},
		shape: {
			type: String,
			default: "circle",
			validator: (value) => {
				return ["circle", "square"].includes(value);
			},
		},
		borderColor: {
			type: String,
			default: "#eee",
		},
		borderWidth: {
			type: Number,
			default: 1,
		},
		uploadText: {
			type: String,
			default: "上传头像",
		},
		action: {
			type: String,
			default: "",
		},
		headers: {
			type: Object,
			default: () => ({}),
		},
		name: {
			type: String,
			default: "file",
		},
	});

	// 定义组件事件
	const emit = defineEmits(["update:value", "success", "error"]);
	// 组件状态
	const avatarUrl = ref(props.value);
	const showActionSheetVisible = ref(false);
	const isReady = ref(false);

	// 操作菜单选项
	const actionSheetItems = [{
		text: "从相册选择"
	}, {
		text: "拍照"
	}];

	// 监听value变化
	watch(
		() => props.value,
		(newVal) => {
			avatarUrl.value = newVal;
		}
	);

	// 组件初始化完成
	onMounted(() => {
		isReady.value = true;
		// 监听保存按钮，然后再执行保存操作  还要继续做监听删除头像按钮
		uni.$on('saveAvatarClicked', () => {
			console.log('监听到保存头像事件');
			// 处理逻辑
		});
	});
	onShow(() => {

	})

	onUnmounted(() => {
		uni.$off('saveAvatarClicked');
	});

	// 处理操作菜单点击
	const handleActionSheet = (e) => {
		showActionSheetVisible.value = false;
		const index = e.detail.index;

		if (index === 0) {
			// 从相册选择
			chooseFromAlbum();
		} else if (index === 1) {
			// 拍照
			takePhoto();
		}
	};

	// 从相册选择图片
	const chooseFromAlbum = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ["original", "compressed"],
			sourceType: ["album"],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0];
				updateAvatar(tempFilePath);
			},
			fail: (err) => {
				emit("error", err);
			},
		});
	};

	// 调用相机拍摄
	const takePhoto = () => {
		uni.chooseImage({
			count: 1,
			sizeType: ["original", "compressed"],
			sourceType: ["camera"],
			success: (res) => {
				const tempFilePath = res.tempFilePaths[0];
				updateAvatar(tempFilePath);
			},
			fail: (err) => {
				emit("error", err);
			},
		});
	};

	// 更新头像
	const updateAvatar = (tempFilePath) => {
		// 更新本地预览
		avatarUrl.value = tempFilePath;
		emit("update:value", tempFilePath);

		// 如果提供了上传接口，则上传到服务器
		if (props.action) {
			uploadToServer(tempFilePath);
		} else {
			emit("success", {
				localUrl: tempFilePath
			});
		}
	};
	// 上传到服务器
	const uploadToServer = (tempFilePath) => {
		const openid = uni.getStorageSync("openid");
		uni.uploadFile({
			url: props.action,
			filePath: tempFilePath,
			name: props.name,
			formData: {
				openid: openid,
				avatar: tempFilePath,
			},
			success: (res) => {
				try {
					const result = JSON.parse(res.data);
					emit("success", result);
					uni.$emit("changeAvater", res.data);
				} catch (e) {
					emit("success", {
						data: res.data
					});
				}
			},
			fail: (err) => {
				emit("error", err);
			},
		});
	};

	// 暴露给父组件的安全方法
	const safeChooseImage = () => {
		if (!isReady.value) {
			console.warn("AvatarUpload component is not ready yet");
			return false;
		}
		chooseFromAlbum();
		return true;
	};

	const safeTakePhoto = () => {
		if (!isReady.value) {
			console.warn("AvatarUpload component is not ready yet");
			return false;
		}
		takePhoto();
		return true;
	};

	// 暴露方法给父组件
	defineExpose({
		chooseImage: safeChooseImage,
		takePhoto: safeTakePhoto,
		isReady: isReady,
	});
</script>

<style scoped lang="scss">
	.avatar-upload-container {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.avatar-container {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		border-style: solid;
		overflow: hidden;
	}

	.avatar-image {
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.default-avatar {
		width: 100%;
		height: 100%;
		background-color: #f5f5f5;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
	}

	.default-avatar-text {
		color: #999;
		font-size: 14px;
	}

	.upload-overlay {
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 40px;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.upload-icon {
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>